<template>
	<gui-page ref="guiPage" :customHeader="true">
		<template v-slot:gHeader>
			<nav-bar-custom left-icon="left" @clickLeftBack="clickLeftBack" :title="$t('Common.palletConsolidation')"
				@clickRight="clickRight" scanType="1"></nav-bar-custom>
		</template>
		<template v-slot:gBody>
			<view class="barcodeSplitting" :style="'height: calc(100vh - ' + navHeight + 'px);'">
				<!-- 扫描模块 -->
				<view class="custom-form-card">
					<view class="custom-card-title">
						<text class="title-line"></text>
						{{ $t('Common.scanTrayBarcode') }}
					</view>
					<!-- 铁托盘 -->
					<view class="gui-form-item gui-border-b" style="padding: 20rpx 0;">
						<text class="item-info-title" style="padding-right: 40rpx;">
							<text class="required-color">*</text>
							{{ $t('Common.tipperTray') }}
						</text>
						<uni-easyinput type="search" :focus="data.isfocus" class="uni-mt-5" suffixIcon="scan"  @focus="getFocus('tcode')"
							v-model="data.tipperTray" :placeholder="$t('Common.scanTipperTray')" @confirm="confirmTipper('tcode')"
							@iconClick="iconClickTipper">
						</uni-easyinput>
					</view>
					<view class="gui-form-item gui-border-b" style="padding: 20rpx 0;">
						<text class="item-info-title" style="padding-right: 40rpx;">
							<text class="required-color">*</text>
							{{ $t('Common.woodenPallet') }}
						</text>
						<uni-easyinput type="search"  class="uni-mt-5" suffixIcon="scan"
							v-model="data.woodenPallet" :placeholder="$t('Common.scanWoodenPallet')" :focus="data.isfocusM"  @focus="getFocus('mcode')" @confirm="confirmWood('mcode')"
							@iconClick="iconClickWood">
						</uni-easyinput>
					</view>
				</view>
				<!-- card模块 -->
				<view v-if="data.ipperLsit" class="custom-form-card">
					<uni-collapse v-model="data.value">
						<uni-collapse-item titleBorder="none" :show-animation="true">
							<template v-slot:title>
								<view class="custom-card-title">
									<text class="title-line"></text>
									{{ $t('Common.currentScaning') }}
								</view>
							</template>
							<!-- card 具体内容 -->
							<view class="content">
								<view class="custom-card-itemOne">
									<text class="item-info-title">{{ $t('distributedEnter.materialCoded')
									}}：</text>{{ data.ipperLsit.barcode }}
								</view>
								<view class="custom-card-itemOne">
									<view class="card-item-50">
										<text class="item-info-title">{{ $t('distributedEnter.materialCode')
										}}：</text>{{ data.ipperLsit.materialCode }}
									</view>
									<view class="card-item-50">
										<text class="item-info-title">{{ $t('distributedEnter.materialName')
										}}：</text>{{ data.ipperLsit.materialName }}
									</view>
								</view>
								<view class="custom-card-itemOne">
									<text class="item-info-title">{{ $t('distributedEnter.materialSpec')
									}}：</text>{{ data.ipperLsit.materialSpec }}
								</view>
								<view class="custom-card-itemOne">
									<!-- <view class="card-item-50">
										<text class="item-info-title">{{ $t('distributedEnter.materialSpec') }}：</text>{{data.ipperLsit.materialSpec}}
									</view> -->
									<view class="card-item-50">
										<text class="item-info-title">{{ $t('distributedEnter.qty')
										}}：</text>{{ data.ipperLsit.currentQty }}
									</view>
								</view>
								<view class="custom-card-itemOne">
									<view class="card-item-50">
										<text class="item-info-title">{{ $t('distributedOut.warehouse')
										}}：</text>{{ data.ipperLsit.warehouseCode }}
									</view>
									<view class="card-item-50">
										<text class="item-info-title">{{ $t('distributedOut.location')
										}}：</text>{{ data.ipperLsit.locationCode }}
									</view>
								</view>
							</view>
						</uni-collapse-item>
					</uni-collapse>
				</view>
				<view class="page-bottom-box">
					<view class="page-bottomBtn bottomBtn-bgcolor-green" @click="handelCommit">{{ $t('calendar.submit') }}
					</view>
				</view>
			</view>
		</template>
	</gui-page>
</template>

<script setup>
import { navigate } from '@/utils/routerSkip.js';
import { useStore } from "vuex";
import { PMScanningBarcode, PalletMerge } from '@/api/api.js';
import { basPdaOperationLogFn } from '@/utils/index.js';
import pdaScan from '@/hooks/pdaScan.js';
import { onBackPress } from '@dcloudio/uni-app';
import { USERINFO, OPERATION_COMMIT, OPERATION_LOOK, OPERATION_SCAN } from '@/constant/index.js'
import {
	ref,
	reactive,
	onMounted,
	watch,
	computed,
	toRaw
} from 'vue';
//JS国际化引入
import { useI18n } from 'vue-i18n';

const {
	scan
} = pdaScan();
const { t } = useI18n();

let store = useStore();
const navHeight = computed(() => {
	return store.state.navHeight
})

const data = reactive({
	tippper: false,//扫描铁托盘的状态
	tipperTray: '', //铁托盘
	woodenPallet: '', // 木托盘
	isfocus: false,
	isfocusM:false,
	value: ['0'],
	scanwoodenList: [], // 木托盘list
	barcodeList: [],
	ipperLsit:'',
	inputType:'tcode'  //扫描类型
})

onMounted(() => {
	uni.$on('scancodedate', (res) => {
		console.log('获取到的code：' + res.code)
		if(data.inputType=='tcode') //光标在铁托盘上
		{
			data.tipperTray=res.code
			confirmTipper('tcode');
		}
		else{ //光标在木托盘上
		    data.woodenPallet=res.code
			confirmWood('mcode');
		}
	})
	setTimeout(() => {  
		data.isfocus = true
	}, 1000)
	
})


//点击物理按键的返回
onBackPress((options) => {
	if (options.from == 'backbutton') {
		if (!data.scanwoodenList.length) {
			uni.navigateBack({
				delta: 1
			});
			return true
		}
		uni.showModal({
			title: t('smashRemoval.warmPrompt'),
			content: t('materials.unsubmittedDataIn'),
			success: function (res) {
				if (res.confirm) {
					//清除store 里面的数据
					store.commit("clearPalletTrayList");
					uni.navigateBack({
						delta: 1
					});
				} else if (res.cancel) {
					console.log('用户点击取消');
				}
			}
		});
		return true;
	}
})

// 获得焦点
const getFocus = (type) => {
	console.log(type)
	data.inputType = type;
	if(data.inputType=='tcode'){
		data.woodenPallet=''  //扫描成功以后将木托盘铁托盘的barcode都清空
	}
}



// 用户点击搜索
const confirmTipper = (type) => {
	data.inputType=type
	data.tippper = true
	getCodeTipper(data.tipperTray, 'keydown', "true")
}
const confirmWood = (type) => {
	data.inputType=type
	console.log(data.tippper)
	if (data.tipperTray == "") {
		uni.showToast({ title: t('Common.scanTipperTrays'), icon: 'none' });
		return
	}
	if (!data.tippper) {
		uni.showToast({ title: t('Common.scanTipperTrays'), icon: 'none' });
		return
	}
	getCodeTipper(data.woodenPallet, 'keydown', "false")
	data.tippper = false
	
	
}

// 用户点击扫码图标
const iconClickTipper = async (type) => {
	if (type === 'suffix') {
		data.inputType='tcode'
		data.tippper = true
		let code = await scan()
		getCodeTipper(code, 'scan', "true")
	}
}

const iconClickWood = async (type) => {
	data.inputType='mcode'
	if (data.tipperTray == "") {
		uni.showToast({ title: t('Common.scanTipperTrays'), icon: 'none' });
		return
	}
	if (!data.tippper) {
		uni.showToast({ title: t('Common.scanTipperTrays'), icon: 'none' });
		return
	}
	if (type === 'suffix') {
		let code = await scan()
		getCodeTipper(code, 'scan', "false")
		data.tippper = false
	}
}

// 将数据存储在vuex
data.scanwoodenList = computed(() => {
	return store.state.palletTrayList
})

// 事件 判断数据
const getCodeTipper = async (code, type, isIron) => {
	console.log(code, data.scanwoodenList)
	// 存储扫描的的条码,通过barode去判断是否有重复
	console.log(`拿到code,code为${code},type类型为${type}`)
	let arrTipper = data.scanwoodenList.filter(x => x.tipperTray == code || x.tipperTray == data.tipperTray); // 铁托盘
	let arr = data.scanwoodenList.filter(x => x.barcode == code || x.barcode == data.woodenPallet); // 木托盘
	if (arrTipper.length > 0) {
		uni.showToast({ title: t('Common.doNotRepeatScanning2'), icon: 'none' });
		return
	}
	if (arr.length > 0) {
		uni.showToast({ title: t('Common.doNotRepeatScanning'), icon: 'none' });
		return
	}
	// 接口需要的参数
	let parmes = {
		barcode: code,
		isIron: isIron,
	}
	// 调用接口
	let res = await PMScanningBarcode(parmes)
	console.log(res)
	try {
		let inputParameter = JSON.stringify(parmes)
		let returnParameter = JSON.stringify(res)
		let operationPicture = '托盘合并'
		let callInterface = res.rquestUrl
		let opertionParmes = {
			inputParameter,
			returnParameter,
			operationPicture,
			callInterface,
			responseCode: res.status,//返回状态
			errorMessage: res.message,//错误信息
			isPass: res.status == 200 ? 'Y' : 'N',//是否成功 Y N
			operationType: OPERATION_SCAN
		}
		basPdaOperationLogFn(opertionParmes)
	} catch (error) {
	}
	if (res.status == 200) {
		console.log(res)
		let tipperTrayBarcode
		if (res.data.isIron) {// 铁托盘返回结果
			tipperTrayBarcode= res.data.barcode
			data.tipperTray=tipperTrayBarcode
			uni.showToast({ title: res.message, icon: 'none' });
			data.isfocusM=true
			data.isfocus=false
		} else { //木托盘返回结果
			// 添加铁托盘barcode
			if (res.data.currentQty == 0) {
				uni.showToast({ title: t('Common.qtyBoundTrays'), icon: "none" })
				return
			}
			let list = res.data;
			list.tipperTray =data.tipperTray
			// 赋值
			data.scanwoodenList.unshift(list)
			data.ipperLsit = res.data
			data.woodenPallet= res.data.barcode
			data.inputType='tcode'

			data.isfocus=true
			data.isfocusM=false
			data.tipperTray=''
			data.woodenPallet=''
			// store.commit('addPalletTrayList',data.scanwoodenList)
		}
	} else {
		uni.showModal({
			content:res.message
		})
		//uni.showToast({ title: res.message, icon: "none",duration:5000 })
		return
	}
}

//  提交
const handelCommit = () => {
	if (data.scanwoodenList.length <= 0) {
		uni.showToast({ title: t('Common.pleaseScanTheCorrect'), icon: 'none' });
		// data.scanwoodenList = []
		return
	}
	//接口参数获取
	let parmes = []
	let items = []
	console.log(data.scanwoodenList)
	data.scanwoodenList.forEach(item => {
		console.log(item.tipperTray)
		items.push(
			{
				barcode: item.tipperTray,
				isIron: true
			},
			{
				barcode: item.barcode,
				isIron: false
			}
		);
		parmes.push({
			"barcodes": items
		})
		items = [];
	})
	console.log(parmes);
	// 添加加载框
	uni.showLoading({
		title: 'loading',
		mask: true
	});
	// 接口
	PalletMerge(parmes).then(res => {
		try {
			let inputParameter = JSON.stringify(parmes)
			let returnParameter = JSON.stringify(res)
			let operationPicture = '托盘合并'
			let callInterface = res.rquestUrl
			let opertionParmes = {
				inputParameter,
				returnParameter,
				operationPicture,
				callInterface,
				responseCode: res.status,//返回状态
				errorMessage: res.message,//错误信息
				isPass: res.status == 200 ? 'Y' : 'N',//是否成功 Y N
				operationType: OPERATION_COMMIT
			}
			basPdaOperationLogFn(opertionParmes)
		} catch (error) {
		}
		if (res.status == 200) {
			//隐藏加载框
			uni.hideLoading();
			uni.showToast({ title: t('Common.trayConsolidation'), icon: 'none' });
			// 提交成功清空数据
			store.commit("clearPalletTrayList");//提交成功清空vuex中的数据，同时领料数量也会自动清空
			data.tipperTray = ""
			data.woodenPallet = ""
			data.ipperLsit = ""
			data.inputType='tcode'
			data.scanwoodenList.length = 0
		} else {
			uni.showToast({ title: res.message, icon: "none" });
		}
	})
}

// 扫描纪录
const clickRight = () => {
	navigate({
		url: '/pages/barcodeManagement/palletConsolidationRecord'
	})
}

//导航栏左侧返回
const clickLeftBack = () => {
	if (!data.scanwoodenList.length) {
		uni.navigateBack({
			delta: 1
		});
		return
	}
	uni.showModal({
		title: t('smashRemoval.warmPrompt'),
		content: t('materials.unsubmittedDataIn'),
		success: function (res) {
			if (res.confirm) {
				store.commit('clearPalletTrayList', data.scanwoodenList)  // 返回清空扫描数据
				uni.navigateBack({
					delta: 1
				});
			} else if (res.cancel) {
				console.log('用户点击取消');
			}
		}
	});
}
</script>


<style lang="scss" scoped>
.barcodeSplitting {
	display: flex;
	flex-direction: column;
	height: calc(100vh - 88rpx);
	// height: 100vh;
}

.distributed-head {
	border-bottom-left-radius: 16rpx;
	border-bottom-right-radius: 16rpx;
}

.scroll {
	flex: 1;
	height: 2rpx;
}

.page-bottom-box {
	position: absolute;
	left: 0px;
	bottom: 0px;
	width: 100%;
}
</style>